package ufp2p;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.io.*;

final class ScreenReader implements Runnable
{

	Socket socket; // socket for the connection

	// Constructor
	public ScreenReader(Socket socket) throws Exception
	{
		this.socket = socket;
		System.out.println("Created screenReader>>>>>>>>>>>>");
	}

	// Implement the run() method of the Runnable interface
	public void run()
	{
		System.out.println("running screenreader thread>>>>>>>>>>>>");
		try
		{
			sendHandshakeMessage();
			//readMyScreen();	//thread constantly calls 
		}
		catch (Exception e)
		{
			try
			{
				this.socket.close();
				System.out.println("Connecetion ForceClosed>>>>>>>>>>>>");
			}
			catch (Exception f)
			{
				System.out.println(f + ">>>>>>>>>>>>"); // print the exception
			}
		}
	}
	
	private void sendHandshakeMessage() throws Exception
	{
		System.out.println(">>>>>>>>>>>>Sending Handshake");
		
		//Send the peerId of this peer while creating - Need to modify it to get it when starting peers later
		HandshakePacket handshake = new HandshakePacket("2011");
		byte[] handshakeMessage = handshake.handshakeMessage();
		this.sendPacket(handshakeMessage);
	}
	
	private void sendPacket(byte[] data) throws Exception
	{
		// Get a reference to the socket's output stream
		DataOutputStream os = new DataOutputStream(	this.socket.getOutputStream());
		
		//Sending data
		os.write(data,0,data.length);
	    os.flush();		
		
	}
	private void readMyScreen() throws Exception
	{
		
		Splitter fileSplit = new Splitter();
		fileSplit.split();
		
		for(int j=1; j <= PeerProcess.NumberOfPieces; j++)
		{
			System.out.println("reading file on PC>>>>>>>>>>>>");
			
			//Access the file
			File myFile = new File (PeerProcess.FileName+ j +".sp");
			int sizeOfMessage = (int)myFile.length();
			byte [] fileContents  = new byte [sizeOfMessage];
			
			//Read the file
			FileInputStream fis = new FileInputStream(myFile);
		    BufferedInputStream bis = new BufferedInputStream(fis);
		    bis.read(fileContents,0,fileContents.length);
			
			//Create the MessagePacket
			MessagePacket thePacket = new MessagePacket(sizeOfMessage, fileContents);
			byte[] toSend = thePacket.getBytesToSend();
			
			//Send the packet
		    System.out.println("Sending Part "+j+"...>>>>>>>>>>>>");
		    String byteArray = new String(toSend);
		    System.out.println(byteArray);
		    
		    sendPacket(toSend);
		    
		    bis.close();
			fis.close();
			
		    System.out.println("File sent!!>>>>>>>>>>>>");
		}
		/*while(true)
		{
			String in = br.readLine();
			System.out.println("Got "+in);
			os.writeBytes(in + '\n');
		      
		}*/


	}

}// end class PeerConnection
